# Virtual Router Simulator 
#
# Copyright (C) 2009-2010 VRSim Project
# Author: Choonho Son <choonho@kt.com>
# URL: <http://vrsim.googlecode.com>
# For license information, see LICENSE.TXT
#

from PyQt4 import QtGui,  QtCore
import VRSim.Globals as globals
from VRSim.Utils import debug,  splash,  message
from VRSim.Ui.Ui_RemoteFolder import Ui_RemoteFolder

class RemoteFolder(QtGui.QDialog,  Ui_RemoteFolder):
    def __init__(self,  filename,  nodeid):
        QtGui.QDialog.__init__(self)
        Ui_RemoteFolder.__init__(self)
        self.setupUi(self)
        
        debug("RemoteFolder nodeid:" + str(nodeid))
        self.rpcinst = globals.GApp.topology.getVMAPI(nodeid)
        
        self.init()
        self.__connectActions()
        self.selectedfile = ""
        
        
    def init(self):
        # show template directory
        self.imgdir = self.rpcinst.getImgDir()
        self.current_imgdir = self.imgdir
        self.mydir = self.rpcinst.getMyDir()
        self.current_mydir = self.mydir
        
        print "current_mydir:",  self.current_mydir
        self.listDir(self.listWidget_Template,  self.current_imgdir)
        self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        
        # show my directory
        
    def __connectActions(self):
        self.connect(self.listWidget_Template,  QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem *)"),  self.actionChangeImgDir)
        self.connect(self.listWidget_MyFolder,  QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem *)"),  self.actionChangeMyDir)
        self.connect(self.listWidget_MyFolder,  QtCore.SIGNAL("itemChanged(QListWidgetItem *)"),  self.actionMyFolderRename)
        # button action
        self.connect(self.pushButton_Copy,  QtCore.SIGNAL("clicked()"),  self.actionCopy)
        self.connect(self.pushButton_Mkdir,  QtCore.SIGNAL("clicked()"),  self.actionMkdir)
        self.connect(self.pushButton_Rename,  QtCore.SIGNAL("clicked()"),  self.actionRename)
        self.connect(self.pushButton_Delete,  QtCore.SIGNAL("clicked()"),  self.actionDelete)
        self.connect(self.pushButton_Upload,  QtCore.SIGNAL("clicked()"),  self.actionUpload)
        self.connect(self.pushButton_Download,  QtCore.SIGNAL("clicked()"),  self.actionDownload)
        
        # Signal for OK, Cancel
        self.connect(self.buttonBox,  QtCore.SIGNAL('accepted()'),  self.__save )
        
    def actionChangeImgDir(self,  item):
        filename = str(item.text())
        if filename[-1] == "/":
            # specific folder (cd filename)
            if self.current_imgdir[-1] == "/":
                self.current_imgdir += filename
            else:
                self.current_imgdir = self.current_imgdir +"/" + filename
            self.listDir(self.listWidget_Template,  self.current_imgdir)
        
        elif filename == ".":
            # nothing 
            pass
        
        elif filename == "..":
            # upperDir (cd ..)
            self.current_imgdir = self.__upperDir(self.current_imgdir)
            # check ROOT Directory
            # cannot overcome MyDIR 
            if self.current_imgdir < self.imgdir:
                self.current_imgdir = self.imgdir
            self.listDir(self.listWidget_Template,  self.current_imgdir)
        
    def actionChangeMyDir(self,  item):
        filename = str(item.text())
        if filename[-1] == "/":
            # specific folder (cd filename)
            if self.current_mydir[-1] == "/":
                self.current_mydir += filename
            else:
                self.current_mydir = self.current_mydir +"/" + filename
            
            self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        
        elif filename == ".":
            # nothing 
            pass
            
        elif filename == "..":
            # upperDir (cd ..)
            self.current_mydir = self.__upperDir(self.current_mydir)
            # check ROOT Directory
            # cannot overcome MyDIR 
            if self.current_mydir < self.mydir:
                self.current_mydir = self.mydir
            self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        else:
            # rename file
            # selected file
            # sourceFile
            src = "%s/%s" % (self.current_mydir,  filename)
            self.myfolder_srcitem = item
            self.myfolder_src = src
            item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable)
            self.listWidget_MyFolder.editItem(item)
            
            

    def actionMyFolderRename(self,  item):
        
        #if self.myfolder_srcitem != item:
        #    msg = "item"
        #    return
        # rename process
        debug("Called actionMyFolderRename")
        src = self.myfolder_src
        dstFile = str(item.text())
        dst = "%s/%s" % (self.current_mydir,  dstFile)
        if src == dst:
            return
        msg = "rename %s to %s" % (src, dst)
        debug(msg)
        tf = self.rpcinst.rename(src,  dst)
        
    ###########################
    # Button Action
    # copy, mkdir, rename, delete
    def actionCopy(self):
        # check selected (sourceFile)
        sourceItem = self.listWidget_Template.currentItem()
        if not sourceItem:
            debug("Template file is not selected")
        file = str(sourceItem.text())
        if file == "." or file == "..":
            debug(". or .. can not be copied")
            return
            
        sourceFile = "%s/%s" % (self.current_imgdir,  str(sourceItem.text()) )
        #TEST
        print "copy ",  sourceFile,  " to ",  self.current_mydir
        self.rpcinst.copy(sourceFile,  self.current_mydir)
        
        self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        
    
    def actionRename(self):
        item = self.listWidget_MyFolder.currentItem()
        if not item:
            # None type
            return
        srcText = str(item.text())
        if srcText == "." or srcText == "..":
            # cannot rename . or ..
            return
            
        srcFolder = self.current_mydir
        src = "%s/%s" % (srcFolder,  srcText)
        # remember previous item
        self.myfolder_srcitem = item
        self.myfolder_src = src
        # change item state
        item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable)
        self.listWidget_MyFolder.editItem(item)
    
    def actionDelete(self):
        item = self.listWidget_MyFolder.currentItem()
        if not item:
            # None type
            return
        srcText = str(item.text())
        if srcText == "." or srcText == "..":
            # cannot rename . or ..
            return
        srcFolder = self.current_mydir
        src = "%s/%s" % (srcFolder,  srcText)
        # remember previous item
        self.myfolder_srcitem = item
        self.myfolder_src = src
        # change item state
        item.setFlags(QtCore.Qt.ItemIsSelectable)
        msg = "Delete %s" % srcText
        ret = QtGui.QMessageBox.warning(None,  "Warning", msg, QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
        if ret == QtGui.QMessageBox.Cancel:
            return
        # delete really
        tf = self.rpcinst.delete(src)
        if tf == False:
            msg = "VMAPI: Cannot delete %s" % srcText
            debug(msg)
        # delete OK
        # refresh list
        self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        
    def actionMkdir(self):
        msg = "Input directory name"
        (text,  ok) = QtGui.QInputDialog.getText(None,  "mkdir",  msg,  QtGui.QLineEdit.Normal,  "dirname")
        if not text or not ok:
            msg = "Mkdir Cancel or no text"
            return
        dirname = "%s/%s" % (self.current_mydir,  text)
        msg = "mkdir %s" % dirname
        tf = self.rpcinst.mkdir(dirname)
        if tf == False:
            msg = "VMAPI: Cannot mkdir directory %s" % msg
            debug(msg)
        # mkdir OK
        # refresh list
        self.listDir(self.listWidget_MyFolder,  self.current_mydir)
        
      
    def actionUpload(self):
        """ upload file to server folder
        """
        filename = QtGui.QFileDialog.getOpenFileName(self, "Choose Upload file",  "", "Config files (*.cfg);;All files (*.*)")
        if filename:
            tf = self.rpcinst.upload(unicode(filename).encode(globals.ENCODING), self.current_mydir)
     
    def actionDownload(self):
        """ download file from server
        """
        item = self.listWidget_MyFolder.currentItem()
        if not item:
            msg = "Select file from MyFolder"
            message(msg)
            return False
            
        text = str(item.text())
        if text == "." or text == "..":
            """ mis choose 
            """
            return
        fullpath = "%s/%s" % (self.current_mydir,  text)
        
        tf = self.rpcinst.download(fullpath)
        
    def listDir(self,  where,  current_dir):
        # clear list
        where.clear()
        # show list
        filelist = self.rpcinst.listDir(current_dir)
        #where.addItems(filelist)
        filelist.sort()
        for file in filelist:
            if file == "." or file == "..":
                # specific file
                item = QtGui.QListWidgetItem()
                item.setText(file)
                item.setTextColor(QtGui.QColor("red"))
            elif file[-1] == "/":
                # directory
                item = QtGui.QListWidgetItem()
                item.setText(file)
                item.setTextColor(QtGui.QColor("blue"))
            else:
                # general file
                item = QtGui.QListWidgetItem()
                item.setText(file)
            where.addItem(item)
            
    # Local method
    def __upperDir(self,  path):
        """ return upperDir
        """
        if path[-1] == "/":
            fullpath = path[1:-2]
        else:
            fullpath = path
        items = fullpath.split("/")
        result = ""
        for item in range(len(items) - 1):
            result = result + "/" + items[item]
        return result
        

    def __save(self):
        """ return filename
        """
        item = self.listWidget_MyFolder.currentItem()
        text = str(item.text())
        if text == "." or text == "..":
            """ mis choose 
            """
            return
        fullpath = "%s/%s" % (self.current_mydir,  text)
        self.selectedfile = fullpath
        
